package com.buho29.rcmanager;

import java.io.InputStream;
import java.util.Locale;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

import com.buho29.rcmanager.bd.DatabaseAdapter;
import com.buho29.rcmanager.bd.TableModel;
import com.buho29.rcmanager.bd.TablePower;
import com.buho29.rcmanager.bd.TablePowerItem;
import com.buho29.rcmanager.utils.Make;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

public class Main extends Activity {
	
    private static final int ACTIVITY_NEW=0;
    private static final int ACTIVITY_EDIT=1;
    private static final int ACTIVITY_PREFERENCE=3; 
    
    private static final int INSERT_ID = Menu.FIRST;
    private static final int PREFERENCE_ID = Menu.FIRST +4;
    
    private static final int DELETE_ID = Menu.FIRST +1;
    private static final int EDIT_ID = Menu.FIRST + 2;
    private static final int STATISTIC_ID = Menu.FIRST + 3;
    
    public static final String CMD="cmd";
    
	private DatabaseAdapter mDbAdapter;
	private TableModel mDbTableModel = new TableModel();
	private AdapterView<Adapter> mGallery;
	
	Handler handLang = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Preferences.loadLanguage(Main.this);
		}
	};
	
	//key  "123456"
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
	        
        handLang.sendEmptyMessageDelayed(0, 1000);
        setContentView(R.layout.gallery);       
        
        mDbAdapter = DatabaseAdapter.getInstance(this);
        mDbTableModel.setSQLiteDatabase(mDbAdapter.getDatabase());
        
        mGallery =  (AdapterView<Adapter>) findViewById(R.id.gallery);
        
        
        mGallery.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                launchPowers(id);
            }
        });
        
        registerForContextMenu(mGallery);
        
        
        populateFields();
    }
    
    @Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		Log.e("RCmanager", "config"+(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE));
	}

	@Override
    public boolean onPrepareOptionsMenu(Menu menu){
	    menu.clear();
        menu.add(0, INSERT_ID,0, R.string.New);
        menu.add(0, PREFERENCE_ID,0, R.string.preference);
        menu.add(0, R.string.scan_QR,0, R.string.scan_QR);	
	    return super.onPrepareOptionsMenu(menu);
    }
    
    @Override
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, DELETE_ID, 0, getString(R.string.delete));
        menu.add(0, EDIT_ID, 0, getString(R.string.edit));
        menu.add(0, STATISTIC_ID, 0, getString(R.string.view));
	}
    
    //selected
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
        case INSERT_ID:
        	launchNewModel();
            return true;
        case PREFERENCE_ID:
            launchPreferences();
            return true;
        case R.string.scan_QR:
        	if(Preferences.neverEncodingQr(this)){
        		IntentIntegrator.initiateScan(this);
        	}else{
        		String msg = getString(R.string.never_encoding_QR_msg)+
        			getString(R.string.encode_QR);
        		new AlertDialog.Builder(this)
        		.setTitle(R.string.never_encoding_QR_title)
        		.setMessage(msg)
        		.setPositiveButton(R.string.ok, null)
        		.show();
        	}
            return true;
	    }        
        return super.onMenuItemSelected(featureId, item);
    }
	
    private void populateFields() {
    	Cursor cur = mDbTableModel.retrieveAll();
    	startManagingCursor(cur);
        mGallery.setAdapter(new ImageAdapter(this,cur));
    	if(cur.getCount()<1)
    		makeAlert().show();
	}
    
    // launch activity
    private void launchModelView(long id) {
    	Intent i = new Intent(Main.this, ModelView.class);
		i.putExtra(TableModel.COL_ROW_ID, id);
        startActivity(i);
	}
    
	private void launchNewModel() {
		Intent i = new Intent(this, ModelEdit.class);
		i.putExtra(CMD, TableModel.CMD_NEW);
		startActivityForResult(i, ACTIVITY_NEW);
	}
	
	private void launchPreferences() {
		Intent i = new Intent(this, Preferences.class);
		startActivityForResult(i, ACTIVITY_PREFERENCE);
	}
	
	private void launchModelEdit(long id) {
		Intent i = new Intent(this, ModelEdit.class);
		i.putExtra(TableModel.COL_ROW_ID, id);
		i.putExtra(CMD, TableModel.CMD_EDIT);
		startActivityForResult(i, ACTIVITY_EDIT);
	}
    
	private void launchPowers(long id) {
		
		Intent i = new Intent(this, PowersView.class);
		i.putExtra(TableModel.COL_ROW_ID, id);
        i.putExtra(PowersView.CMD, PowersView.CMD_MODEL);
		startActivity(i);
	}
	
    private void launchChrono(long powerId) {
	    Intent i = new Intent(this, ChronoView.class);
	    i.putExtra(TablePowerItem.COL_ROW_ID, powerId);
	    i.putExtra(CMD, ChronoView.CMD_1);
	    startActivity(i); 
	}
	
    //selected
    @Override
	public boolean onContextItemSelected(MenuItem item) {
    	final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch(item.getItemId()) {
	    	case DELETE_ID:
		        
		        mDbTableModel.setId(info.id);
		        mDbTableModel.load();
		        
		        Make.dialogConfirm(this,getText(R.string.delete)+" "+mDbTableModel.getName()+"?")
		        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
		        	public void onClick(DialogInterface dialog, int whichButton) {
		        		
		        		mDbAdapter.deleteModel(info.id);
		        		populateFields();
		        	}
		        }).create().show();
		        
		        
		        return true;
		    case EDIT_ID:
		        launchModelEdit(info.id);
		        return true;
		    case STATISTIC_ID:
		        launchModelView(info.id);
		        return true;
		}
		return super.onContextItemSelected(item);
	}
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        
        switch(requestCode) {
	        case ACTIVITY_NEW:
	            populateFields();
	            return;
	        case ACTIVITY_EDIT:
	            populateFields();
	            return;
        }
        
        IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
        if (scanResult != null) {
        	String result = scanResult.getContents();
        	if(result != null){
        		try {
					final long powerItemId = Long.parseLong(result);
					
					TablePower tbPower = new TablePower();
					tbPower.setSQLiteDatabase(mDbAdapter.getDatabase());
					
					Cursor cur = tbPower.fetchModels(powerItemId);
					startManagingCursor(cur);
					
					if(cur != null && cur.moveToFirst()){
						if(cur.getCount()>1){
							
							final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
								R.layout.list_item_b, cur, new String[] {TableModel.COL_NAME},
								new int[] { R.id.text1 });

							String namePowerItem = cur.getString(cur.getColumnIndex(TablePower.COL_NAME_POWER_ITEM));
							
							new AlertDialog.Builder(this)
							.setTitle(String.format(getString(R.string.scan_choice_title),namePowerItem))
							.setAdapter(adapter, new OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									long powerId = adapter.getItemId(which);
									launchChrono(powerId);
								}
							}).show();
						}else{
							long powerId = cur.getLong(cur.getColumnIndex(TablePower.COL_ROW_ID));
							launchChrono(powerId);
						}
					}else Toast.makeText(this, R.string.scan_not_found, Toast.LENGTH_LONG).show();
					
				} catch (NumberFormatException e) {
					Toast.makeText(this, R.string.scan_error, Toast.LENGTH_LONG).show();
				}
        	}
        }
    }

	/////////////////////////
    
	private AlertDialog makeAlert() {
		
		return new AlertDialog.Builder(Main.this)
			.setIcon(R.drawable.alert_dialog_icon)
			.setTitle(R.string.emptyModel)
			.setMessage(R.string.emptyModelMessage)
			.setPositiveButton(R.string.New, new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int whichButton) {
			    	launchNewModel();
			    }
			})
			.setNeutralButton(R.string.loadDemo, new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int whichButton) {
			    	loadDemo();
			    	populateFields();
			    }
			})
			.setNegativeButton(R.string.cancel, null)
			.setCancelable(false)
			.create();
	}
    
    protected void loadDemo() {
		mDbAdapter.loadDemo();
	}

	/////////////////////////
    
    public static class ImageAdapter extends BaseAdapter {
        
        private Context mContext;
        private Cursor mCursor;
        private LayoutInflater inflater;
    	private int mWidthImg;
    	private int mHeighImg;
        
        public ImageAdapter(Context c ,Cursor cursor) {
            mContext = c;
            mCursor = cursor;
            inflater = LayoutInflater.from(c);
            
            final float scale = c.getResources().getDisplayMetrics().density;
            mWidthImg = (int) (240 * scale);
            mHeighImg = (int) (160 * scale);
        }

        public int getCount() {
            return mCursor.getCount();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
        	mCursor.moveToPosition(position);
        	int index = mCursor.getColumnIndexOrThrow(TableModel.COL_ROW_ID);
        	long t = mCursor.getLong(index);
            return t;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
        	
			ViewHolder holder;
			
			if (convertView == null) {
					
	        	convertView = inflater.inflate(R.layout.gallery_item, null);
	        	
				holder = new ViewHolder();
				holder.text = (TextView) (TextView) convertView.findViewById(R.id.tv);
				holder.icon = (ImageView) (ImageView) convertView.findViewById(R.id.iv);
				
				convertView.setTag(holder);
				
			}else holder = (ViewHolder) convertView.getTag();
			
            
            mCursor.moveToPosition(position);
            String path = mCursor.getString(mCursor.getColumnIndexOrThrow(TableModel.COL_IMAGE));
            String name = mCursor.getString(mCursor.getColumnIndexOrThrow(TableModel.COL_NAME));

            holder.text.setText(name);
            if(path != null){
            	InputStream source;
				try {
					//source = mContext.getContentResolver().openInputStream(Uri.parse(path));
	    			Bitmap bmp = BitmapFactory.decodeFile(path);//.decodeStream(source);
	    			//bmp = croppedBitmap(bmp, mWidthImg, mHeighImg);
	            	holder.icon.setImageBitmap(bmp);
				} catch (Exception e) {
					holder.icon.setImageResource(R.drawable.no_found_image);
				}
            }else{
            	holder.icon.setImageResource(R.drawable.no_found_image);
            }
            
            return convertView;
        }
        
        int mLabel;
        
    }
    
	static class ViewHolder {
		TextView text;
		ImageView icon;
	} 
    
    
}